#-*- encoding: gb2312 -*-  
import sys  
import pamie as p
import pywintypes
import urllib2
import time
import urllib
from ntlm import HTTPNtlmAuthHandler
reload(sys)   
sys.setdefaultencoding('gb2312') 


def downloadFile(url,dest):
	user = "fanying"
	password = "fany@1234"
	passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
	passman.add_password(None, url, user, password)
	# create the NTLM authentication handler
	auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

	# create and install the opener
	opener = urllib2.build_opener(auth_NTLM)
	urllib2.install_opener(opener)

	# retrieve the result
	response = urllib2.urlopen(url)
	#print(response.read())
	
	data = response.read()
	with open(dest + "/new"+str(time.time())+"_test.zip", "wb") as code:
		code.write(data)
#-*- encoding: gb2312 -*-  

# 2 args : ln(link, string) ; dest(destination,string)
def getSubLinks(ln,dest):
	tmp = p.PAMIE(ln)
	tmp.navigate(ln)
	slns = tmp.getLinks()
	
	for m in range(1,len(slns)):
		if slns[m].getAttribute('href').find('.rar') > 0 :
			try:
				ln = slns[m].getAttribute('href')
				#print  ln
				#print "'r'"+ln
				ln = ln.replace('\\','\\')

				downloadFile(ln,dest)
				
			except pywintypes.com_error:
				print "get some error"
				continue
	tmp.quit()